package Oracle;

import java.io.File;
import java.io.IOException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: 2006-3-29
 * Time: 14:50:53
 * 提供简单的功能函数
 */
public class Func {
    /**
     * 计算2个日期之间的相差的:星期数/天数/小时数/分钟数/秒数
     */
    public static final int DIFF_SECONDS = 1;
    public static final int DIFF_MINUTES = 2;
    public static final int DIFF_HOURS = 3;
    public static final int DIFF_DAYS = 4;
    public static final int DIFF_WEEKS = 5;
    public static final int DIFF_MONTHS = 6;
    public static final int DIFF_YEARS = 7;

    protected static final int DIV_SECONDS = 1000;
    protected static final int DIV_MINUTES = DIV_SECONDS * 60;
    protected static final int DIV_HOURS = DIV_MINUTES * 60;
    protected static final int DIV_DAYS = DIV_HOURS * 24;
    protected static final int DIV_WEEKS = DIV_DAYS * 7;

    public static final String LOGIN_REDIRECT_KEY = "redirect";

    /**
     * 返回指定日期格式的字符串
     *
     * @param date   要转换的日期
     * @param format 要转换的日期的格式:
     *               Letter  Date or Time Component  Presentation  Examples
     *               G  Era designator  Text  AD
     *               y  Year  Year  1996; 96
     *               M  Month in year  Month  July; Jul; 07
     *               w  Week in year  Number  27
     *               W  Week in month  Number  2
     *               D  Day in year  Number  189
     *               d  Day in month  Number  10
     *               F  Day of week in month  Number  2
     *               E  Day in week  Text  Tuesday; Tue
     *               a  Am/pm marker  Text  PM
     *               H  Hour in day (0-23)  Number  0
     *               k  Hour in day (1-24)  Number  24
     *               K  Hour in am/pm (0-11)  Number  0
     *               h  Hour in am/pm (1-12)  Number  12
     *               m  Minute in hour  Number  30
     *               s  Second in minute  Number  55
     *               S  Millisecond  Number  978
     *               z  Time zone  General time zone  Pacific Standard Time; PST; GMT-08:00
     *               Z  Time zone  RFC 822 time zone  -0800
     * @return 格式化以后的字符串, 如果format为null或者为""的话，返回2005-08-07 19:06
     */
    public static String formatDate(Date date, String format) {
        return DateUtils.formatDate(date, format);
    }

    public static class DateUtils {
        /**
         * 返回指定日期格式的字符串
         *
         * @param date   要转换的日期
         * @param format 要转换的日期的格式:
         *               Letter  Date or Time Component  Presentation  Examples
         *               G  Era designator  Text  AD
         *               y  Year  Year  1996; 96
         *               M  Month in year  Month  July; Jul; 07
         *               w  Week in year  Number  27
         *               W  Week in month  Number  2
         *               D  Day in year  Number  189
         *               d  Day in month  Number  10
         *               F  Day of week in month  Number  2
         *               E  Day in week  Text  Tuesday; Tue
         *               a  Am/pm marker  Text  PM
         *               H  Hour in day (0-23)  Number  0
         *               k  Hour in day (1-24)  Number  24
         *               K  Hour in am/pm (0-11)  Number  0
         *               h  Hour in am/pm (1-12)  Number  12
         *               m  Minute in hour  Number  30
         *               s  Second in minute  Number  55
         *               S  Millisecond  Number  978
         *               z  Time zone  General time zone  Pacific Standard Time; PST; GMT-08:00
         *               Z  Time zone  RFC 822 time zone  -0800
         * @return 格式化以后的字符串, 如果format为null或者为""的话，返回2005-08-07 19:06
         */
        public static String formatDate(Date date, String format) {
            if (date == null) {
                return "";
            }
            if (format == null || format.equals("")) {
                format = "yyyy-MM-dd HH:mm";
            }
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
            return simpleDateFormat.format(date);
        }

        /**
         * 将字符串转换为日期
         *
         * @param dateString dateString
         * @param format     format to use, 参见formatDate的定义
         * @return dateString
         */
        public static Date parse(String dateString, String format) {
            if (dateString == null || dateString.length() <= 0) {
                return null;
            }
            if (format == null || format.equals("")) {
                format = "yyyy-MM-dd HH:mm:ss";
            }
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            Date ret;
            try {
                ret = sdf.parse(dateString);
            }
            catch (Exception e) {
                ret = null;
                e.printStackTrace();
            }
            return ret;
        }

        /**
         * 计算2个日期之间的相差的天数/小时数/分钟数/秒数, date1 - date2
         *
         * @param date1 日期1
         * @param date2 日期2
         * @param type  相差的类型
         *              <pre>
         *                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          DIFF_SECONDS
         *                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          DIFF_MINUTES
         *                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          DIFF_HOURS
         *                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          DIFF_DAYS
         *                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          DIFF_WEEKS
         *                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          DIFF_MONTHS	目前不支持
         *                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          DIFF_YEARS	目前不支持
         *                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 </pre>
         * @return date1 - date2 by type
         */
        public static int diffDate(Date date1, Date date2, int type) {
            if (date1 == null) {
                date1 = new Date();
            }
            if (date2 == null) {
                date2 = new Date();
            }
            int diffRet;
            long diff = date1.getTime() - date2.getTime();
            switch (type) {
                case DIFF_SECONDS:
                    diffRet = (int) (diff / DIV_SECONDS);
                    break;
                case DIFF_MINUTES:
                    diffRet = (int) (diff / DIV_MINUTES);
                    break;
                case DIFF_HOURS:
                    diffRet = (int) (diff / DIV_HOURS);
                    break;
                case DIFF_DAYS:
                    diffRet = (int) (diff / DIV_DAYS);
                    break;
                case DIFF_WEEKS:
                    diffRet = (int) (diff / DIV_WEEKS);
                    break;
//            case DIFF_MONTHS:
//                break;
//            case DIFF_YEARS:
//                break;
                default:
                    throw new NullPointerException("Not support in current version");
            }
            return diffRet;
        }

        /**
         * 计算两个日期之间相差多少天,如果是大于1天的放回  xx天,如果小于1天的返回 xx小时xx分钟xx秒
         *
         * @param date1 java.util.Date
         * @param date2 java.util.Date
         * @return xx天或者xx小时xx分钟xx秒
         */
        public static String formatDiffDate(Date date1, Date date2) {
            String ext;
            int diffRet = diffDate(date1, date2, DIFF_DAYS);
            if (diffRet > 0) {
                ext = String.format("%d天", diffRet);
            } else {
                diffRet = diffDate(date1, date2, DIFF_SECONDS);
                if (diffRet > 0) {
                    ext = String.format("%d小时%d分钟%d秒", diffDate(date1, date2, DIFF_HOURS), diffDate(date1, date2, DIFF_MINUTES) - diffDate(date1, date2, DIFF_HOURS) * 60, diffDate(date1, date2, DIFF_SECONDS) - diffDate(date1, date2, DIFF_MINUTES) * 60);
                } else {
                    ext = "";
                }
            }
            return ext;
        }

        /**
         * 用于建立一个空的日期对象,对象的默认值是1900-01-01
         *
         * @return return a default date
         */
        public static Date getEmptyDate() {
            return getString2ShortDate("1900-01-01");
        }

        /**
         * 用于建立一个空的日期对象,对象的默认值是1900-01-01
         *
         * @return return empty date string
         */
        public static String getEmptyDateString() {
            return "1900-01-01";
        }

        private static synchronized Date getString2Date(String format, String str) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
            simpleDateFormat.applyPattern(format);
            ParsePosition parseposition = new ParsePosition(0);
            return simpleDateFormat.parse(str, parseposition);
        }

        public static Date getString2LongDate(String str) {
            return getString2Date(DATEFORMATLONG, str);
        }

        public static Date getString2MediumDate(String str) {
            return getString2Date(DATEFORMATMEDIUM, str);
        }

        public static Date getString2ShortDate(String str) {
            return getString2Date(DATEFORMATSHORT, str);
        }

        public static final String DATEFORMATLONG = "yyyy-MM-dd HH:mm:ss";
        public static final String DATEFORMATMEDIUM = "yyyy-MM-dd HH:mm";
        public static final String DATEFORMATSHORT = "yyyy-MM-dd";
    }

    /**
     * 文字截断，并加"..."
     *
     * @param string string to be boxed
     * @param length 可显示长度
     * @return 截断文字
     */
    public static String boxString(String string, int length) {
        //TODO 需完善
        if (string == null || length <= 0) {
            return "";
        }
        //string.getBytes("").length
        return string.length() > length ? string.substring(0, length - 2) + "..." : string;
    }

    //服务段验证类
    public static class Validator {

        //验证email的正则表达式
        protected static final String EmailRegex = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";
        //验证电话号码的正则表达式
        protected static final String PhoneRegex = "(^[0-9]{3,4}\\-[0-9]{6,8}\\-[0-9]{1,5}$)|(^[0-9]{3,4}\\-[0-9]{6,8}$)|(^[0-9]{6,8}\\-[0-9]{1,5}$)|(^[0-9]{6,8}$)";
        //验证手机号码的正则表达式
        protected static final String MobileRegex = "^((\\(\\d{3}\\))|(\\d{3}\\-))?(13|15)\\d{9}$";
        //验证URL的正则表达式
        protected static final String UrlReges ="^http:\\/\\/[A-Za-z0-9]+\\.[A-Za-z0-9]+[\\/=\\?%\\-&_~`@\\[\\]\\':+!]*([^<>\\\"\\\"])*$";


        //判断是否是字符串s是否是emial格式
        public static boolean isEmial(String s) {
            return !(s == null || s.trim().equals("")) && validate(s, EmailRegex);
        }

        //判断是否是字符串s是否是电话号码格式，电话号码格式包括（021-50801234-8016/021-50801234/50801234/50801234-8016）3种
        public static boolean isPhone(String s) {
            return !(s == null || s.trim().equals("")) && validate(s, PhoneRegex);
        }

        //判断是否是字符串s是否是手机号码格式，手机号码格式(13*********); 
        public static boolean isMobilePhone(String s) {
            return !(s == null || s.trim().equals("")) && validate(s, MobileRegex);
        }

        //判断是否是字符串s是否符合url格式，url格式为http:x.x.x.x...(注，x表示1个或者多个字符)
        public static boolean isUrl(String s) {
            return !(s == null || s.trim().equals("")) && validate(s, UrlReges);
        }

        protected static boolean validate(String s, String regex) {
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(s);
            return m.matches();
        }
    }

    /**
     * 可以用于sql语句的辅助工具
     */
    public static class SqlUtils {
        /**
         * 生成指定数量的参数符，如 (?,?,?,?)
         * @param size
         * @return
         */
        public static String genQuestionMarks(int size) {
            String qmarks = " ("; //left
            for (int i = 0; i < size; i++) {
                if (i > 0) {
                    qmarks += ",";
                }
                qmarks += "?";
            }
            qmarks += ") ";
            return qmarks;
        }

        /**
         * 合并参数，返回新的参数数组
         *
         * @param params
         * @param newParams
         * @return
         */
	    public static Object[] mergeParams(Object[] params, Object[] newParams) {
            if (params != null && newParams != null) {
                Object[] ps = new Object[params.length + newParams.length];
                System.arraycopy(params, 0, ps, 0, params.length);
                System.arraycopy(newParams, 0, ps, params.length, newParams.length);
                return ps;
            } else {
                return params;
            }
        }

        public static Object[] mergeParams(Object[] params, int[] newParams) {
            if (params != null && newParams != null) {
                Object[] ps = new Object[params.length + newParams.length];
                System.arraycopy(params, 0, ps, 0, params.length);
                for (int i = params.length; i < ps.length; i++) {
                    ps[i] = (Integer) newParams[i - params.length];
                }
                return ps;
            } else {
                return params;
            }
        }

        public static Object[] mergeParams(Object[] params, long[] newParams) {
            if (params != null && newParams != null) {
                Object[] ps = new Object[params.length + newParams.length];
                System.arraycopy(params, 0, ps, 0, params.length);
                for (int i = params.length; i < ps.length; i++) {
                    ps[i] = (Long) newParams[i - params.length];
                }
                return ps;
            } else {
                return params;
            }
        }
        
        public static String getStringValue( String str ) {
        	return str.replaceAll("\\'", "''");
        }
        
        public static String getLikeString( String str ) {
        	return "%" + getStringValue(str).replaceAll("\\*", "%") + "%";
        }

        /**
         * 判断是否为数字（包含小数）
         * @param str	待判断的字符串
         * @return
         */
        public static boolean isNumber(String str) { //检查字符串是否为数字
    		if(str.length() == 0) {
    			return false;
    		}
    		
    		for (int i = 0; i < str.length(); i++) {
    			if((str.charAt(i) < '0' || str.charAt(i) > '9')&&str.charAt(i)!='.'){
    				return false;
    			}
    		}
    		return true;
    	}
        
        /**
         * 判断是否为纯数字
         * @param str 待判断的字符串
         * @return
         */
        public static boolean isPureNumber(String str) { //检查字符串是否为数字
            str=str.trim();
    		if(str.length() == 0) {
    			return false;
    		}
    		
    		for (int i = 0; i < str.length(); i++) {
    			if(str.charAt(i) < '0' || str.charAt(i) > '9'){
    				return false;
    			}
    		}
    		return true;
    	}
    }
    
  //param folderPath 文件夹完整绝对路径

    public static void delFolder(String folderPath) {
    try {
       delAllFile(folderPath); //删除完里面所有内容
       String filePath = folderPath;
       filePath = filePath.toString();
       java.io.File myFilePath = new java.io.File(filePath);
       myFilePath.delete(); //删除空文件夹
    } catch (Exception e) {
      e.printStackTrace(); 
    }
}

//删除指定文件夹下所有文件
//param path 文件夹完整绝对路径
  public static boolean delAllFile(String path) {
      boolean flag = false;
      File file = new File(path);
      if (!file.exists()) {
        return flag;
      }
      if (!file.isDirectory()) {
        return flag;
      }
      String[] tempList = file.list();
      File temp = null;
      for (int i = 0; i < tempList.length; i++) {
         if (path.endsWith(File.separator)) {
            temp = new File(path + tempList[i]);
         } else {
             temp = new File(path + File.separator + tempList[i]);
         }
         if (temp.isFile()) {
            temp.delete();
         }
         if (temp.isDirectory()) {
            delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
            delFolder(path + "/" + tempList[i]);//再删除空文件夹
            flag = true;
         }
      }
      return flag;
    }
  
//删除指定文件夹下所有文件
//param path 文件夹完整绝对路径
  public static List<String> getFileList(String path) {

	  List<String> fileList = new ArrayList<String>();
      File file = new File(path);
      if (!file.exists()) {
        return fileList;
      }
      if (!file.isDirectory()) {
    	  fileList.add(path);
    	  return fileList;
      }
      String[] tempList = file.list();
      File temp = null;
      for (int i = 0; i < tempList.length; i++) {
         if (path.endsWith(File.separator)) {
            temp = new File(path + tempList[i]);
         } else {
             temp = new File(path + File.separator + tempList[i]);
         }
         if (temp.isFile()) {
        	 fileList.add(temp.getAbsolutePath());
         }
         if (temp.isDirectory()) {
        	 fileList.addAll(getFileList(temp.getAbsolutePath()));
         }
      }
      return fileList;
    }
  
  public static void makeDir(String dir)
  {
	  String curdir = "";
	  dir = dir.replaceAll("\\\\", "/");
	  while(dir.indexOf('/') != -1)
	  {
			curdir = curdir + dir.substring(0,dir.indexOf('/')+1);
			dir = dir.substring(dir.indexOf('/')+1);
			java.io.File folder = new java.io.File(curdir);
			if(!folder.exists())
			{
				folder.mkdir();
			}
	  }
  }
  
//  public static void makeDir(FtpClient ftpClient, String dir) throws IOException
//  {
//	  String curdir = "";
//	  dir = dir.replaceAll("\\\\", "/");
//	  while(dir.indexOf('/') != -1)
//	  {
//			curdir = curdir + dir.substring(0,dir.indexOf('/')+1);
//			dir = dir.substring(dir.indexOf('/')+1);
//
//			if(curdir.length()>0 && curdir.compareTo("\\") != 0 && curdir.compareTo("/") != 0)
//			{
//				ftpClient.sendServer("mkd " + curdir + "\r\n");
//			}
//	  }
//  }
}

